package com.example.star.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiFavorite;
import com.example.star.entity.Favorite;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageZoomDialogFragment;
import com.example.star.view.center.ShoppingCartActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PerimeterDetailActivity extends AppCompatActivity {
    private String userName;
    private boolean isCurrentlyFavorite = false; // 用于记录当前商品是否已收藏
    private ImageButton favoriteButton; // 声明收藏按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_perimeter_detail);

        // 获取传递过来的数据
        String starName = getIntent().getStringExtra("starName");
        String perimeterTitle = getIntent().getStringExtra("perimeterTitle");
        String prices = getIntent().getStringExtra("prices");
        String imageResource = getIntent().getStringExtra("imageResource");
        String productType = getIntent().getStringExtra("productType");
        String freight = getIntent().getStringExtra("freight");
        String deliveryAddress = getIntent().getStringExtra("deliveryAddress");

        // 查找视图组件
        ImageButton backButton = findViewById(R.id.back_button);
        favoriteButton = findViewById(R.id.favorite); // 初始化收藏按钮
        ImageButton shopCartButton = findViewById(R.id.shopping_cart);
        ImageView imageView = findViewById(R.id.image_perimeter_detail);
        TextView starNameTextView = findViewById(R.id.star_name_detail);
        TextView perimeterTitleTextView = findViewById(R.id.perimeter_title_detail);
        TextView priceTextView = findViewById(R.id.price_detail);
        TextView productTypetView = findViewById(R.id.producttype);
        TextView freightTextView = findViewById(R.id.freight);
        TextView deliveryAddressTextView = findViewById(R.id.delivery_address);
        TextView addShopCartButton = findViewById(R.id.add_shopping_cart);
        TextView buyNowButton = findViewById(R.id.buy_now);

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", "");

        // 初始检查收藏状态
        checkFavoriteStatus(perimeterTitle);

        //收藏按钮
        favoriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCurrentlyFavorite) {
                    // 已收藏，执行删除操作
                    deleteFavorite(perimeterTitle);
                } else {
                    // 未收藏，执行收藏逻辑
                    Favorite favorite = new Favorite();
                    favorite.setUserName(userName);
                    favorite.setImageResource(imageResource);
                    favorite.setStarName(starName);
                    favorite.setTitle(perimeterTitle);
                    favorite.setProductType(productType);
                    favorite.setPrices(prices);
                    favorite.setFreight(freight);
                    favorite.setDeliveryAddress(deliveryAddress);
                    // 这里需要实现保存收藏的接口调用
                    saveFavorite(favorite);
                }
            }
        });

        //购物车
        shopCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PerimeterDetailActivity.this, ShoppingCartActivity.class);
                startActivity(intent);
            }
        });

        //加入购物车
        addShopCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PerimeterDetailActivity.this, AddShopCartActivity.class);
                intent.putExtra("userName", userName);
                intent.putExtra("starName", starName);
                intent.putExtra("perimeterTitle", perimeterTitle);
                intent.putExtra("prices", prices);
                intent.putExtra("imageResource", imageResource);
                intent.putExtra("productType", productType);
                intent.putExtra("freight", freight);
                intent.putExtra("deliveryAddress", deliveryAddress);
                startActivity(intent);
            }
        });

        //立即购买
        buyNowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PerimeterDetailActivity.this, BuyNowActivity.class);
                intent.putExtra("userName", userName);
                intent.putExtra("starName", starName);
                intent.putExtra("perimeterTitle", perimeterTitle);
                intent.putExtra("prices", prices);
                intent.putExtra("imageResource", imageResource);
                intent.putExtra("productType", productType);
                intent.putExtra("freight", freight);
                intent.putExtra("deliveryAddress", deliveryAddress);
                startActivity(intent);
            }
        });

        // 先设置默认图片
        imageView.setImageResource(R.drawable.register);

        // 检查 imageResource 是否为 null
        if (imageResource != null) {
            try {
                // 尝试当作本地资源 ID 处理
                int imageResId = getResources().getIdentifier(imageResource, "drawable", getPackageName());
                if (imageResId != 0) {
                    imageView.setImageResource(imageResId);
                } else {
                    // 若不是有效的本地资源 ID，尝试使用 Glide 加载，可能是网络图片
                    Glide.with(PerimeterDetailActivity.this)
                            .load(imageResource)
                            .placeholder(R.drawable.register) // 加载中显示的图片
                            .error(R.drawable.register) // 加载失败显示的图片
                            .into(imageView);
                }
            } catch (Exception e) {
                // 出现异常，使用 Glide 加载，可能是网络图片
                Glide.with(PerimeterDetailActivity.this)
                        .load(imageResource)
                        .placeholder(R.drawable.register)
                        .error(R.drawable.register)
                        .into(imageView);
            }

            // 设置头像点击监听器
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String imageUrl = imageResource;
                    ImageZoomDialogFragment dialogFragment = ImageZoomDialogFragment.newInstance(imageUrl);
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    dialogFragment.show(fragmentManager, "image_zoom_dialog");
                }
            });
        }

        // 设置 TextView 的文本内容
        starNameTextView.setText(starName);
        perimeterTitleTextView.setText(perimeterTitle);
        priceTextView.setText(String.valueOf(prices));
        productTypetView.setText(String.valueOf(productType));
        freightTextView.setText(String.valueOf(freight));
        deliveryAddressTextView.setText(String.valueOf(deliveryAddress));
    }

    private void checkFavoriteStatus(String perimeterTitle) {
        ApiFavorite favoriteService = ApiClient.getApiFavorite();
        Call<Boolean> call = favoriteService.checkFavorite(userName, perimeterTitle);
        call.enqueue(new Callback<Boolean>() {
            @Override
            public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = response.body();
                    if (isCurrentlyFavorite) {
                        // 更新按钮图标或文本为删除状态
                        favoriteButton.setImageResource(R.drawable.ic_delete); // 假设存在删除图标资源
                    } else {
                        // 更新按钮图标或文本为收藏状态
                        favoriteButton.setImageResource(R.drawable.ic_favorite); // 假设存在收藏图标资源
                    }
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(PerimeterDetailActivity.this, "检查收藏状态失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(PerimeterDetailActivity.this, "检查收藏状态失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Boolean> call, Throwable t) {
                Toast.makeText(PerimeterDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveFavorite(Favorite favorite) {
        // 实现保存收藏的接口调用
        ApiFavorite favoriteService = ApiClient.getApiFavorite();
        // 假设存在保存收藏的接口方法 saveFavorite，根据实际情况调整
        Call<Favorite> call = favoriteService.saveFavorite(favorite);
        call.enqueue(new Callback<Favorite>() {
            @Override
            public void onResponse(Call<Favorite> call, Response<Favorite> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = true;
                    // 更新按钮图标或文本为删除状态
                    favoriteButton.setImageResource(R.drawable.ic_delete);
                    Toast.makeText(PerimeterDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(PerimeterDetailActivity.this, "收藏失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(PerimeterDetailActivity.this, "收藏失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Favorite> call, Throwable t) {
                Toast.makeText(PerimeterDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void deleteFavorite(String perimeterTitle) {
        ApiFavorite favoriteService = ApiClient.getApiFavorite();
        Call<Void> call = favoriteService.deleteFavorite(userName, perimeterTitle);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    isCurrentlyFavorite = false;
                    // 更新按钮图标或文本为收藏状态
                    favoriteButton.setImageResource(R.drawable.ic_favorite);
                    Toast.makeText(PerimeterDetailActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(PerimeterDetailActivity.this, "取消收藏失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(PerimeterDetailActivity.this, "取消收藏失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(PerimeterDetailActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}